package com.example.demo.java8.functionalinterface.day240427;

import com.google.common.util.concurrent.*;

import java.util.concurrent.Executors;

/**
 * https://blog.csdn.net/Primary_wind/article/details/131843355
 *
 * @author luo
 * @since 2024/4/27 15:07
 */
public class ListenableFutureExample {
    public static void main(String[] args) {
        ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));
        ListenableFuture<Integer> future = executorService.submit(() -> {
            // 模拟在执行过程中抛出异常
            //throw new RuntimeException("Exception in task");
            System.out.println("执行到这里了");
            return 88;
        });

        FutureCallback<Integer> callback = new FutureCallback<Integer>() {
            @Override
            public void onSuccess(Integer result) {
                // 这部分代码在任务完成后异步执行，不会中断主线程
                System.out.println("Result: " + result);
            }

            @Override
            public void onFailure(Throwable t) {
                // 这部分代码在任务执行过程中抛出异常后异步执行，不会中断主线程
                System.err.println("Error occurred in callback: " + t.getMessage());
                throw new RuntimeException("Exception in callback"); // 在回调中再次抛出异常
            }
        };

        Futures.addCallback(future, callback, executorService);

        try {
            // 等待任务完成
            Integer result = future.get();
            System.out.println("异步获取到的结果为"+result);
        } catch (Exception e) {
            // 在主线程捕获异常
            System.err.println("Caught exception in main thread: " + e.getMessage());
        }

        // 主线程继续执行
        System.out.println("Main thread continues.");

        // 关闭线程池
        executorService.shutdown();
    }


}
